import utils.TreeNode;

import java.util.ArrayList;

/**
 * @author ZCR
 * @create 2025/9/4 23:55
 */
public class Solution129 {
    int sum = 0;
    StringBuilder path = new StringBuilder();

    public int sumNumbers(TreeNode root) {
        backtrack(root);
        return sum;
    }

    public void backtrack(TreeNode root) {
        path.append(root.val);
        if (root.left == null && root.right == null) {
            sum += Integer.parseInt(path.toString());
        }
        if (root.left != null) {
            backtrack(root.left);
        }
        if (root.right != null) {
            backtrack(root.right);
        }
        path.deleteCharAt(path.length() - 1);
    }
}
